package com.hs.wa.utls;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SpringUtils implements ApplicationContextAware {

    // applicationContext
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext1) throws BeansException {
        applicationContext = applicationContext1;
    }

    // 从ApplicationContext 中获取Bean(根据类加载)(这个applicationContext已经在启动的时候就加载过了)
    public static <T> T getBean(Class<T> tClass){
        return applicationContext.getBean(tClass);
    }

    // 从ApplicationContext 中获取Bean(根据类型加载)
    public static <T> T getBean(String name, Class<T> type) {
        return applicationContext.getBean(name, type);
    }

    // 从ApplicationContext 中获取Environment,然后再获取配置文件中的数据(指定key的值)
    public static String getConfigValue(String key){
        Environment environment = getBean(Environment.class);
        String prop = environment.getProperty(key);
        return prop;
    }

    // 与上面的区别在于可能获取到的prop可能不是一个值, 可能还有多个子节点值
    public static List<String> getConfigValueList(String key){
        Environment environment = getBean(Environment.class);
        String prop = environment.getProperty(key);
        List<String> items = new ArrayList<>();
        if (StringUtils.isBlank(prop)) {
            return items;
        }
        for (String item : prop.split(",")) {
            item = item.trim();
            if (StringUtils.isNotBlank(item)) {
                items.add(item);
            }
        }
        return items;
    }


}